package com.example.famhealing.schedule;

import java.net.URL;
import java.util.Calendar;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.example.famhealing.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

//투약일정 추가 액티비티
public class AddMeditationActivity extends Activity implements OnClickListener, OnLongClickListener{
	
	ImageButton prevButton, confirmButton, morningAlarm, noonAlarm, nightAlarm, otherAlarm, everyDay;
	
	TextView morningTime, noonTime, nightTime, otherTime;
	
	CheckBox cb1, cb2, cb3, cb4, cb5, cb6, cb7;
	
	String selectedDay = "";
	
	private int mHour, mMinute;
	
	//timepicker가 총 4개 들어가므로 각각 구분을 위함
	static final int MORNING_TIMEPICKER = 0;
	static final int NOON_TIMEPICKER = 1;
	static final int NIGHT_TIMEPICKER = 2;
	static final int OTHER_TIMEPICKER = 3;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meditation);
        
        prevButton = (ImageButton)findViewById(R.id.prevButton);
        confirmButton = (ImageButton)findViewById(R.id.confirmButton);
        morningAlarm = (ImageButton)findViewById(R.id.morningAlarm);
        noonAlarm = (ImageButton)findViewById(R.id.noonAlarm);
        nightAlarm = (ImageButton)findViewById(R.id.nightAlarm);
        otherAlarm = (ImageButton)findViewById(R.id.otherAlarm);
        everyDay = (ImageButton)findViewById(R.id.everyDay);
        
        morningTime = (TextView)findViewById(R.id.morningTime);
        noonTime = (TextView)findViewById(R.id.noonTime);
        nightTime = (TextView)findViewById(R.id.nightTime);
        otherTime = (TextView)findViewById(R.id.otherTime);
        
        cb1 = (CheckBox)findViewById(R.id.monday);
        cb2 = (CheckBox)findViewById(R.id.tuesday);
        cb3 = (CheckBox)findViewById(R.id.wednsday);
        cb4 = (CheckBox)findViewById(R.id.thursday);
        cb5 = (CheckBox)findViewById(R.id.friday);
        cb6 = (CheckBox)findViewById(R.id.saturday);
        cb7 = (CheckBox)findViewById(R.id.sunday);
        
        prevButton.setOnClickListener(this);
        confirmButton.setOnClickListener(this);
        morningAlarm.setOnClickListener(this);
        noonAlarm.setOnClickListener(this);
        nightAlarm.setOnClickListener(this);
        otherAlarm.setOnClickListener(this);
        everyDay.setOnClickListener(this);
        
        morningTime.setOnClickListener(this);
        noonTime.setOnClickListener(this);
        nightTime.setOnClickListener(this);
        otherTime.setOnClickListener(this);
        
        morningTime.setOnLongClickListener(this);
        noonTime.setOnLongClickListener(this);
        nightTime.setOnLongClickListener(this);
        otherTime.setOnLongClickListener(this);
        
	}
	
	public String checkDay() {
		if(cb1.isChecked())
        	selectedDay += "월/";
        if(cb2.isChecked())
        	selectedDay += "화/";
        if(cb3.isChecked())
        	selectedDay += "수/";
        if(cb4.isChecked())
        	selectedDay += "목/";
        if(cb5.isChecked())
        	selectedDay += "금/";
        if(cb6.isChecked())
        	selectedDay += "토/";
        if(cb7.isChecked())
        	selectedDay += "일/";
        
        //선택된 요일들을 selectedDay에 저장(서버에 요청 보내는 형태로)
        selectedDay = selectedDay.substring(0,selectedDay.lastIndexOf("/"));
        
        return selectedDay;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()) {
			case R.id.prevButton :
				finish();
				break;
			case R.id.confirmButton :
				selectedDay = checkDay();
				Toast.makeText(AddMeditationActivity.this, selectedDay, Toast.LENGTH_SHORT).show();
				//new AddMeditationSchedule().execute();
				break;
			case R.id.morningAlarm :
				break;
			case R.id.noonAlarm :
				break;
			case R.id.nightAlarm :
				break;
			case R.id.otherAlarm :
				break;
			case R.id.everyDay :
				//매일마다 버튼을 터치하면 모든 요일에 체크됨
				cb1.setChecked(true);
				cb2.setChecked(true);
				cb3.setChecked(true);
				cb4.setChecked(true);
				cb5.setChecked(true);
				cb6.setChecked(true);
				cb7.setChecked(true);
				break;
			case R.id.morningTime:
				showDialog(MORNING_TIMEPICKER);
				break;
			case R.id.noonTime:
				showDialog(NOON_TIMEPICKER);
				break;
			case R.id.nightTime:
				showDialog(NIGHT_TIMEPICKER);
				break;
			case R.id.otherTime:
				final Calendar c = Calendar.getInstance();
				mHour = c.get(Calendar.HOUR_OF_DAY);
				mMinute = c.get(Calendar.MINUTE);
				showDialog(OTHER_TIMEPICKER);
				break;
		}
	}
	
	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		
		//각 해당하는 시간 길게 터치시 초기화
		switch(v.getId()) {
		case R.id.morningTime:
		    morningTime.setText("00:00");
			break;
		case R.id.noonTime:
			noonTime.setText("00:00");
			break;
		case R.id.nightTime:
			nightTime.setText("00:00");
			break;
		case R.id.otherTime:
			otherTime.setText("00:00");
			break;
		}
		
		//길게 터치 후 onClick이벤트 발생 막기위해 true 반환
		return true;
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
			case MORNING_TIMEPICKER:
				return new TimePickerDialog(this, myMorningTimeSetListener, 8, 00, false);
			case NOON_TIMEPICKER:
				return new TimePickerDialog(this, myNoonTimeSetListener, 12, 00, false);
			case NIGHT_TIMEPICKER:
				return new TimePickerDialog(this, myNightTimeSetListener, 18, 00, false);
			case OTHER_TIMEPICKER:
				return new TimePickerDialog(this, myOtherTimeSetListener, mHour, mMinute, false);
			default:
				return null;
	    }
	}
	  
	//아침 timepicker timeset 리스너
	private TimePickerDialog.OnTimeSetListener myMorningTimeSetListener
		= new TimePickerDialog.OnTimeSetListener(){

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			
			String time = "Hour: " + String.valueOf(hourOfDay) + "\n"
					+ "Minute: " + String.valueOf(minute);
	    
			morningTime.setText(String.valueOf(hourOfDay)+":"+String.valueOf(minute));
	    
			Toast.makeText(AddMeditationActivity.this, time, Toast.LENGTH_SHORT).show();
		}
	};
	 
	//점심 timepicker timeset 리스너
	private TimePickerDialog.OnTimeSetListener myNoonTimeSetListener
		= new TimePickerDialog.OnTimeSetListener(){

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			String time = "Hour: " + String.valueOf(hourOfDay) + "\n"
					+ "Minute: " + String.valueOf(minute);
	    
			noonTime.setText(String.valueOf(hourOfDay)+":"+String.valueOf(minute));
	    
			Toast.makeText(AddMeditationActivity.this, time, Toast.LENGTH_SHORT).show();
		}
	};
	
	//저녁 timepicker timeset 리스너
	private TimePickerDialog.OnTimeSetListener myNightTimeSetListener
	 	= new TimePickerDialog.OnTimeSetListener(){

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			String time = "Hour: " + String.valueOf(hourOfDay) + "\n"
					+ "Minute: " + String.valueOf(minute);
	    
			nightTime.setText(String.valueOf(hourOfDay)+":"+String.valueOf(minute));
	    
			Toast.makeText(AddMeditationActivity.this, time, Toast.LENGTH_SHORT).show();
		}
	};
	
	//기타 timepicker timeset 리스너
	private TimePickerDialog.OnTimeSetListener myOtherTimeSetListener
	  	= new TimePickerDialog.OnTimeSetListener(){

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			String time = "Hour: " + String.valueOf(hourOfDay) + "\n"
					+ "Minute: " + String.valueOf(minute);
	    
			otherTime.setText(String.valueOf(hourOfDay)+":"+String.valueOf(minute));
	    
			Toast.makeText(AddMeditationActivity.this, time, Toast.LENGTH_SHORT).show();
		}
	};

	/*
    private class AddMeditationSchedule extends AsyncTask<Void, Void, String> {	

		@Override
		protected String doInBackground(Void... params) {
			// TODO Auto-generated method stub
			
			String url = "http:// 54.250.182.202:8080/famhealing/setMeditationSchedule.set?" +
					"time=날짜시간&phone_num=전화번호&medicine=약이름&week_day=요일들&time=시간들&num=투약횟수&alarm=(on off)";
		
			String error = "";
			
			try {
				
				//Post				
				
				URL urladdr = new URL(url);
				
				//Parsing
				boolean inTitle1 = false;
		  			
		  		XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
		  			
		  		XmlPullParser parser = parserCreator.newPullParser(); 
		  		parser.setInput(urladdr.openStream(), "UTF-8");
		  		
		  		int parserEvent = parser.getEventType(); 
		  		
		  		String tag;
		  		
		  		while(parserEvent != XmlPullParser.END_DOCUMENT) {
		  			switch(parserEvent) {
		  			case XmlPullParser.START_DOCUMENT:
		  				break;
		  			case XmlPullParser.END_DOCUMENT:
		  				break;
		  			case XmlPullParser.START_TAG:
		  				tag = parser.getName();
		  				if(tag.equals("error")) {
		  					inTitle1 = true;
		  				}
		  				break;
		  			case XmlPullParser.TEXT:
		  				//tag = parser.getName();
		  				if(inTitle1) {
		  					error = parser.getText();
		  					inTitle1 = false;
		  				}
		  				break;
		  			case XmlPullParser.END_TAG:
		  				break;
		  			}
		  			parserEvent = parser.next();	
		  		}
		  			
		  	} catch (Exception e) {
		  			Log.e("dd", "Error in network call", e);
		  	}
			
			return error;
		}
		
		protected void onPostExecute(String error) {
			
			if(error.equals("0")){
				
				Toast.makeText(AddMeditationActivity.this, "일정 추가 성공!", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(AddMeditationActivity.this, "일정 추가 실패!", Toast.LENGTH_SHORT).show();
			}
			
			super.onPostExecute(error);
		}
	}
	*/
    
}
